package com.jn.algorithm.day021.question64;

import java.util.Arrays;

/**
 * @author 江南大学1033190417
 * @date 2022/5/13 22:54
 */
public class Solution {

    //动态规划
    public int minPathSum(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int[][] dp = new int[m + 2][n + 2];
        for (int i = 0; i < m + 2; i++) {
            Arrays.fill(dp[i], Integer.MAX_VALUE);
        }
        dp[1][1] = grid[0][0];
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (i == 1 && j == 1) {
                    continue;
                }
                int m1 = Math.min(dp[i - 1][j], dp[i + 1][j]);
                int m2 = Math.min(dp[i][j - 1], dp[i][j + 1]);
                dp[i][j] = Math.min(m1, m2) + grid[i - 1][j - 1];
            }
        }
        return dp[m][n];
    }

    public void print(int[][] arr) {
        int m = arr.length;
        int n = arr[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(arr[i][j] + "\t\t\t\t");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] grid = new int[][]{
                {1, 3, 1},
                {1, 5, 1},
                {4, 2, 1},
        };
        System.out.println(solution.minPathSum(grid));
    }

}
